import io from 'socket.io-client'
import store from './store/store';




export const getSocket = (() => {
    let socket = null;
    return user_id => {
        // 判断连接并返回正确的单个socket对象
        // 在重新连接的时候会产生连个socket连接,但在一段时间后其中一个会自动断开
        if (!socket) {
            // 没有socket对象
            socket = io('http://localhost:8000', {
                query: {
                    user_id: user_id ?? store.getState().user.id
                }
            });
            const originDisconnect = socket.disconnect.bind(socket);
            socket.disconnect = () => {
                originDisconnect();
                socket = null;
            }
            return socket;
        }
        return socket;
    }
})();




// 进入room页触发开始监听群组
export const joinRoom = roomArr => getSocket().emit('joinRoom', roomArr);
// 停止socket监听
export const exitSocket = () => getSocket().disconnect();

// 监听后台发送的退出登录
export const onQuitLog = callback => getSocket().on('quitLog', callback);
export const offQuitLog = () => getSocket().off('quitLog');

// 监听不同群组的新信息
export const onSocketRoomMessage = (group_id, callback) => getSocket().on(`roomMessage${group_id}`, callback);
export const offSocketRoomMessage = group_id => getSocket().off(`roomMessage${group_id}`);

// 监听用户的系统消息
export const onSocketSystemMessage = (user_id, callback) => getSocket().on(`systemMessage${user_id}`, callback);
export const offSocketSystemMessage = user_id => getSocket().off(`systemMessage${user_id}`);


// 在管理确认加入群组后,后台要发送一个socket让在线用户的群组列表出现刚加入的群组
// 确认用户加入群组
export const onJoinGroup = callback => getSocket().on('joinGroup', callback);
export const offJoinGroup = () => getSocket().off('joinGroup');

// 退出群组的消息监听
export const onGroupQuit = callback => getSocket().on('groupQuit', callback);
export const offGroupQuit = () => getSocket().off('groupQuit');

